/*
 ************************************************************************************
 *  Copyright www.ebidding.com.cn 2014-09-17 Authors: 闫广坤 <ygk@ebidding.com.cn> *
 ************************************************************************************
 */
package com.exercise.utils;


import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.TypeReference;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：闫广坤
 * 创建时间：2014-09-17
 * 功能描述：json装换。
 * 版本:2.0.0。
 */
public class JsonUtils {


    private final static ObjectMapper objectMapper;
    private final static ObjectMapper objectMapperNotNull;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        objectMapperNotNull = new ObjectMapper();
        objectMapperNotNull.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        objectMapperNotNull.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T toBean(String content, Class<T> valueType) {

        try {
            return objectMapper.readValue(content, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T toBean(String content, TypeReference valueTypeRef) {

        try {
            return objectMapper.readValue(content, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> List<T> toList(String content, Class<T> valueType) {

        try {
            JsonParser parser = objectMapper.getJsonFactory().createJsonParser(content);

            JsonNode nodes = parser.readValueAsTree();
            List<T> list = new ArrayList<T>(nodes.size());
            for (JsonNode node : nodes) {
                list.add(objectMapper.readValue(node, valueType));
            }

            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toJSon(Object object) {

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String toJSonNotNull(Object object) {

        try {
            return objectMapperNotNull.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
